# 1. This file is used to replicate all results appearing in the paper and SM
# 2. It will read estimation results stored in the "estimate" folder
#    generated by the markdown files "replications.Rmd" 
# 3. If the "estimate" folder is empty, please run the markdown file
#    "replications.Rmd" first before running this file

############################
## Set Path
############################

rm(list = ls())
### Please set path to the root folder of the project ###
path <- "~/Dropbox/projectZ/IV Sensitivity/LLXZ_rep/" # please change this line
setwd(path)

############################
## Install Packages
############################

# define a function to install packages
installed_pkgs <- installed.packages()[, "Package"]
install_all <- function(packages) {
  for (pkg in packages) {
    if (!pkg %in% installed_pkgs) {
      install.packages(pkg)
    }
  }
}

# install packages from CRAN
packages <- c("AER", "broom", "data.table", "devtools", "doParallel", "dplyr", "estimatr", "fixest", 
    "foreach", "fwildclusterboot", "future", "ggfortify", "ggplot2", "glue", 
    "haven", "ivDiag", "ivmodel", "janitor", "kableExtra", "knitr", "latex2exp", "lfe", "magrittr", "mc2d", 
    "mvtnorm", "pacman", "patchwork", "remotes", "rio", "tictoc", "testthat", "wCorr")
install_all(packages)

# install from github
if (!"LalRUtils"  %in% installed_pkgs) {
  devtools::install_github("apoorvalal/LalRUtils")
}

############################
## Run all files
############################

# We recommend excuting these files one by one

source("code/0_merge.R")
source("code/1_stats.R")
source("code/2_Fstats.R")
source("code/3_inference.R")
source("code/4_discrepancy.R")
source("code/5_sim_continuous.R") 
source("code/6_sim_binary.R")
source("code/7_sim_Fstats.R")
source("code/8_zfs_sims.R")
source("code/9_zfs_application.R")

